<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, onUpdated, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import MeScroll from 'mescroll.js'
import 'mescroll.js/mescroll.min.css'
const { proxy } = getCurrentInstance()

/* ---- */
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []
const forFees = proxy.$Fees || []

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = reactive({
  info: '',
  btnTxt: '我要赞助',
  // ----
  title: '',
  // ----
  share_title: proxy.$shareTitle,
  share_desc: proxy.$shareDesc,
  share_icon: proxy.$shareIcon,
  // ----
  sponsorId: undefined,
  sponsorStatus: false,
  sponsorWork: false,
  // ----
  sponsPayId: 0,
  sponsFeeId: 'sponsorPush',
  sponsFeeVal: 0,
  sponsFeeNum: 0,
  sponsFeeUnit: '',
  sponsFeeUse: true,
  // ----
  power: 1
})
// ----
const forFree = 9 / 5
const setTrueStyle = ref({})
// ----
const moveTime = 50
let showMarquee = null
// --mescroll--
const noData = proxy.$Global.noData
let mescroll = null
const items = ref([])

/* ---- */
const preImg = ref()
const layer = ref()
const layerBox = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const getTrueStyle = () => {
  if (proxy.$refs.forTrueWidth) {
    const imgEL = proxy.$refs.forTrueWidth
    const imgRatio = forFree
    setTrueStyle.value = { height: `${Math.round(imgEL.offsetWidth / imgRatio)}px` }
  }
}
// ----
const setMarquee = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    const forLi = el.innerHTML
    if (Number(el.firstChild.offsetWidth) > Number(el.offsetWidth)) {
      el.innerHTML = forLi + forLi
      showMarquee = setInterval(marqueefun, moveTime)
    }
  }
}
const marqueefun = () => {
  if (proxy.$refs.forMarquee) {
    const el = proxy.$refs.forMarquee.querySelector('ul')
    if (Number(el.lastChild.offsetWidth) <= Number(el.scrollLeft)) {
      el.scrollLeft = el.scrollLeft - el.firstChild.offsetWidth
    } else {
      el.scrollLeft = el.scrollLeft + 1
    }
  }
}
const stopRolling = () => {
  if (showMarquee) {
    clearInterval(showMarquee)
    showMarquee = null
  } else {
    showMarquee = setInterval(marqueefun, moveTime)
  }
}
// ----
const getCurrencyInfo = async (callback) => {
  // --获取组织会费--
  forFees.some((item) => {
    if (String(item.id) === String(user.sponsFeeId)) {
      user.sponsFeeVal = Number(item.amount)
      user.sponsFeeNum = Number(item.num)
      user.sponsFeeUnit = item.typeText
      user.sponsFeeUse = item.isOpenUse
    }
  })
  // ----
  if (Number(Object.keys(logUser).length) > 0 && user.sponsFeeUse) {
    user.power = 2
    // --获取充值有效期--
    let workLine = []
    proxy.$Myfun.getJsonData(logUser.topupze, (resJson) => { workLine = resJson })
    let amountDateRetail = 0
    workLine.some((oneItem) => {
      if (String(oneItem.id) === String(user.sponsFeeId)) {
        oneItem.info.some((twoItem) => {
          if (String(twoItem.id) === String(user.sponsPayId)) amountDateRetail = Date.parse(new Date(twoItem.endtime.replace(/-/g, '/'))) || 0
        })
      }
    })
    const curDate = Date.parse(new Date())
    user.sponsorWork = Number(amountDateRetail) >= Number(curDate)
    // --获取是否曾经赞助--
    await proxy.$http.get('meeting-organiser/index', {
      params: { 'MeetingOrganiserSearch[dealer_id]': logUser.id }
    }).then((res) => {
      if (Number(res.items.length) > 0) {
        user.sponsorId = res.items[0].id
        user.sponsorStatus = Number(res.items[0].status) === 1
      }
    })
    // ----
    if (user.sponsorWork) {
      user.btnTxt = '修改我的'
      if (!user.sponsorStatus && Number(user.sponsorId) > 0) user.btnTxt = '等待审核'
    } else if (Number(amountDateRetail) > 0) {
      user.btnTxt = '再次赞助'
    }
  }
  // --获取赞助推广信息--
  const sponsorData = forSys.filter((item) => { return String(item.name) === 'market_sponsor' })
  if (Number(sponsorData.length) === 1) {
    const SSData = sponsorData[0]
    await proxy.$Myfun.getJsonData(SSData.value, (resJson) => {
      const curRes = resJson[0] || {}
      // ----
      if (curRes.remark && Number(curRes.remark.length) > 0) user.info = proxy.$Myfun.setText(curRes.remark)
      // ----
      user.title = proxy.$Myfun.setText(curRes.title)
      if (curRes.share_title) user.share_title = proxy.$Myfun.setText(curRes.share_title)
      if (curRes.share_desc) user.share_desc = proxy.$Myfun.setText(curRes.share_desc)
      if (curRes.share_img && Number(curRes.share_img.length) > 0) user.share_icon = curRes.share_img[0].image
    })
  }
  // ----
  if (user.info) nextTick(() => { setMarquee() })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
  // ----
  callback && callback()
}
// --getData--
const startMeScroll = () => {
  mescroll = new MeScroll(proxy.$refs.dataScroll, {
    up: {
      callback: getListData,
      isBounce: false,
      page: { num: 0, size: 10 },
      htmlNodata: '<p class="upwarp-nodata">-- 到底啦 --</p>',
      noMoreSize: 10,
      toTop: {
        src: '/pics/mescroll-totop.png',
        offset: 1000
      },
      empty: {
        warpId: proxy.$refs.dataList,
        tip: noData
      }
    }
  })
}
const getListData = (page) => {
  getListDataFromNet({
    forUrl: 'meeting-organiser/index',
    forData: {
      params: {
        'MeetingOrganiserSearch[status]': 1,
        sort: 'SORT_DESC',
        // ----
        page: page.num,
        PageSize: page.size
      }
    }
  }, page.num, page.size, (curPageData) => {
    setListData(curPageData).then((result) => {
      mescroll.endSuccess(curPageData ? curPageData.length : 0, true)
      items.value = items.value.concat(result)
    })
  }, (resMsg) => {
    mescroll.endErr()
    proxy.$Myfun.forToast(layer.value, 'open', resMsg)
  })
}
const getListDataFromNet = (option, pageNum, pageSize, successCallback, errorCallback) => {
  if (Number(pageNum) === 1) {
    if (document.querySelector('.upwarp-nodata')) { document.querySelector('.upwarp-nodata').style.visibility = 'hidden' }
    items.value = []
  }
  // ----
  proxy.$http.get(option.forUrl, option.forData).then((res) => {
    successCallback && successCallback(res.items)
  }).catch((err) => { errorCallback && errorCallback(err) })
}
const setListData = async (items) => {
  const newItems = []
  for (let i = 0; i < Number(items.length); i++) {
    const item = items[i]
    // ----
    let forDesc = ''
    await proxy.$Myfun.getJsonData(item.remark, (resJson) => {
      if (Number(resJson.length) > 0) {
        if (Number(resJson[0].desc.length) > 0) forDesc = proxy.$Myfun.setText(resJson[0].desc)
      }
    })
    // ----
    let forWechatImg = ''
    await proxy.$Myfun.getJsonData(item.qrcode_image, (resJson) => {
      if (Number(resJson.length) > 0) forWechatImg = resJson[0].image
    })
    // ----
    let forImg = ''
    const advItems = []
    await proxy.$Myfun.getJsonData(item.ads_image, (resJson) => {
      if (Number(resJson.length) > 0) forImg = resJson[0].image
      // ----
      resJson.forEach((curItem) => {
        advItems.push({
          msrc: curItem.image,
          src: curItem.image,
          width: curItem.width,
          height: curItem.height,
          alt: ''
        })
      })
    })
    // ----
    newItems.push({
      id: item.id,
      name: proxy.$Myfun.setText(item.name),
      desc: forDesc,
      leader: proxy.$Myfun.setText(item.delegate),
      telphone: item.telphone,
      wechat_img: forWechatImg,
      image: forImg,
      advs: advItems,
    })
  }
  return newItems
}
const divScroll = (event) => { proxy.$Myfun.setImgToTop() }
// ----
const getHeadFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      if (Number(user.power) === 1) {
        proxy.$Myfun.openPage(proxy, 'push', 'UserLogin', { toBack: true })
        return false
      }
      // ----
      if (user.sponsorWork) {
        if (!user.sponsorStatus && Number(user.sponsorId) > 0) return false
        // ----
        proxy.$Myfun.openPage(proxy, 'push', 'SponsorInfo', { id: user.sponsorId })
      } else {
        const options = {
          type: 6,
          maxCount: 5,
          title: '你给我赞助，我给你推广',
          content: '费用：' + user.sponsFeeVal.toFixed(2) + '元/' + user.sponsFeeNum + user.sponsFeeUnit,
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: '我要赞助',
            class: 'xw-color-24',
            callback: (count) => {
              layerBox.value.close()
              // ----
              const forToPay = { payType: user.sponsFeeId, regType: 'jobs', payId: user.sponsPayId, payIdKey: 'jobs_id', payCount: count }
              let forExtend = { name: 'SponsorInfo' }
              if (Number(user.sponsorId) > 0) forExtend = { name: 'SponsorInfo', opts: { id: user.sponsorId } }
              proxy.$Myfun.openPage(proxy, 'push', 'PaySys', { toPay: JSON.stringify(forToPay), exTend: JSON.stringify(forExtend) })
            }
          }],
          callback: (count) => {
            layerBox.value.layer.content = '费用：' + Number(user.sponsFeeVal * count).toFixed(2) + '元/' + Number(user.sponsFeeNum * count) + user.sponsFeeUnit
          }
        }
        proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      }
      break
    }
  }
}
const getAuditFun = (type, item, event) => {
  switch (Number(type)) {
    case 1: {
      if (Number(item.advs.length) > 0) {
        const curEL = event.currentTarget
        const options = {
          actElement: curEL,
          addopt: {
            loop: true,
            dataSource: item.advs
          }
        }
        proxy.$Myfun.isIndepth(preImg.value, 'openPhotoSwipe', options)
      }
      break
    }
    case 2: {
      let forDesc = '<div style="line-height: 2.5rem; text-align: justify;"><b>' + item.name + '</b><div>'
      if (item.desc && Number(item.desc.length) > 0) forDesc = '<div style="line-height: 2.5rem; text-align: justify;"><b style="display: block; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 1px solid #d7d7d7;">' + item.name + '</b>' + item.desc + '<div>'
      const options = {
        type: 3,
        content: forDesc
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
    case 3: {
      window.location.href = 'tel:' + item.telphone
      break
    }
    case 4: {
      let options = {
        title: proxy.$Global.layer.titleTwo + item.telphone,
        content: proxy.$Global.layer.conEver,
        button: [{
          text: proxy.$Global.layer.btnCancel
        }, {
          text: proxy.$Global.layer.btnAsk,
          class: 'xw-color-24',
          callback: () => { window.location.href = 'tel:' + item.telphone }
        }]
      }
      if (item.wechat_img) {
        options = {
          title: proxy.$Global.layer.titleThree,
          content: '<div style="padding: 0 2.4rem;"><img src="' + item.wechat_img + '" style="width: 100%;"/></div>',
          button: [{
            text: proxy.$Global.layer.btnCancel
          }, {
            text: proxy.$Global.layer.btnAsk,
            class: 'xw-color-24',
            callback: () => { window.location.href = 'tel:' + item.telphone }
          }]
        }
      }
      proxy.$Myfun.isIndepth(layerBox.value, 'open', options)
      break
    }
  }
}

/* ---- */
onMounted(() => {
  setTimeout(() => { getTrueStyle() }, 100)
  // ----
  getCurrencyInfo(() => {
    // --创建MeScroll对象--
    setTimeout(() => { startMeScroll() }, 500)
  })
})
onUpdated(() => { nextTick(() => { proxy.$Myfun.setSectionH() }) })
onBeforeRouteLeave(() => { if (mescroll) mescroll.destroy() })
</script>

<template>
  <div>
    <header class="xw-bg-gray">
      <div class="forTop xw-bgCL-11 xw-flex xw-flex-align">
        <div class="TOP-msg xw-Lfg xw-flex-W1">
          <div class="forMarquee" v-if="user.info">
            <div ref="forMarquee" class="FMQ-con xw-act xw-flex xw-flex-align" @click="stopRolling">
              <ul class="xw-flex-W1">
                <li>{{user.info}}</li>
              </ul>
            </div>
          </div>
        </div>
        <span class="TOP-submit xw-act xw-bgCL-20 xw-radius-3" @click="getHeadFun(1)" v-if="user.sponsFeeUse">{{user.btnTxt}}</span>
      </div>
    </header>
    <div class="xw-section">
      <div ref="dataScroll" class="mescroll" @scroll="divScroll">
        <ul class="list-user xw-flex xw-flex-column" ref="dataList">
          <li class="xw-bg-white xw-radius-3" v-for="(item, index) in items">
            <div class="LUR-name xw-act xw-ellipsis-2" @click="getAuditFun(1, item, $event)" v-if="item.name">{{item.name}}</div>
            <div class="LUR-img xw-act" :style="setTrueStyle" @click="getAuditFun(1, item, $event)" v-if="item.image"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.image + ')' }"></div></div>
            <div class="LUR-info xw-flex xw-flex-align">
              <div class="xw-flex-W1 xw-ellipsis"><span>业务负责：</span>{{item.leader}}</div>
              <a class="LUR-btn xw-Rfg xw-flex xw-flex-align" @click="getAuditFun(2, item)"><em class="fal fa-book-open-cover xw-color-1"></em></a>
              <a class="LUR-btn xw-Rfg xw-flex xw-flex-align" @click="getAuditFun(3, item)"><em class="fal fa-phone-volume xw-color-3"></em></a>
              <a class="LUR-btn xw-flex xw-flex-align" @click="getAuditFun(4, item)"><em class="fal fa-comments xw-color-7"></em></a>
            </div>
          </li>
          <div class="list-li"><div ref="forTrueWidth"></div></div>
        </ul>
      </div>
    </div>
    <preImg-view ref="preImg"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layer"/>
  </div>
</template>

<style scoped>
/* ---- */
.TOP-msg { padding: 0 0 0 0.4rem; }
.TOP-msg:before { top: 0.2rem; bottom: 0.2rem; width: 0.8rem; background: #ffffff; }

/* ---- */
.forMarquee { height: 100%; padding: 0 1rem; }
.FMQ-con { height: 100%; }
.FMQ-con ul { white-space: nowrap; overflow: hidden; }
.FMQ-con li { display: inline-block; font-size: 1.7rem; font-weight: bold; }

/* ---- */
.list-user li { position: relative; margin: 1rem 1rem 0; overflow: hidden; }
.LUR-name { padding: 1rem; line-height: 2.5rem; font-size: 1.7rem; font-weight: bold; text-align: justify; }
.LUR-info { padding: 1rem; }
.LUR-btn { padding: 0 1.2rem; }
.LUR-btn em { font-size: 2rem; }
.LUR-btn:last-of-type { padding-right: 0; }
.list-li { margin: 0 1rem; }
</style>